package com.starblink.mine.personhome.ui

import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.ext.ApolloModelExt.isFansOpen
import com.starblink.android.basic.ext.ApolloModelExt.isFollowOpen
import com.starblink.android.basic.ext.ApolloModelExt.isLikeOpen
import com.starblink.android.basic.ext.ApolloModelExt.isPostOpen
import com.starblink.android.basic.ext.ApolloModelExt.isWishlistOpen
import com.starblink.android.basic.ext.ApolloValSetExt.apolloValue
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.user.UserRelationCodeEnum
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowUserEvent
import com.starblink.android.basic.util.bus.bean.LikePostEvent
import com.starblink.android.basic.util.bus.bean.PersonInfoModified
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.util.post.PostUtils
import com.starblink.android.basic.widget.ConfirmDialog
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.R
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.FormatUtils
import com.starblink.feedback.ui.PersonalHomeObjectiveMoreDialog
import com.starblink.feedback.ui.PersonalHomeObjectiveMoreDialog.Companion.ARG_RESULT
import com.starblink.feedback.ui.PersonalHomeObjectiveMoreDialog.Companion.RESULT_CLICK_BLOCK
import com.starblink.mine.databinding.ActivityPersonHomeBinding
import com.starblink.mine.personhome.ui.like.ui.LikeFragment
import com.starblink.mine.personhome.ui.post.ui.PostFragment
import com.starblink.mine.personhome.ui.widget.TabViewHolder
import com.starblink.mine.personhome.ui.wishlist.ui.WishlistFragment
import com.starblink.rocketreserver.fragment.AccountF
import com.starblink.share.view.ShareDialog
import com.starblink.share.view.utils.ShareTypeEnum
import com.starblink.share.view.utils.ShareUrlUtils
import kotlin.math.absoluteValue

/**
 * 个人首页
 * @note 主态（我的个人首页）和客态（其他用户个人首页）复用同一个页面
 */
@Route(path = RoutePage.Mine.PERSON_HOME, extras = RoutePage.Extra.NEED_LOGIN)
class PersonHomeActivity : BaseTVMActivity<ActivityPersonHomeBinding, PersonHomeVM>() {
    private val sharedViewModel by viewModels<SharedViewModel>()

    @Autowired(name = MineManager.KEY_PAGE_TYPE)
    @JvmField
    var pageType: Int = MineManager.PersonHomePageType.MINE

    // 何时传入？（1）客态（2）通知链接或外部链接跳转
    @Autowired(name = MineManager.KEY_USER_ID)
    @JvmField
    var accountId: String = ""

    /**
     * 用户是否已删除
     * 仅客态时传入，传入数据可能不是最新的，依然需要请求用户信息获取最新状态，该参数作用仅用于改善用户交互
     * #note 可以不传
     */
    @Autowired(name = MineManager.KEY_ACCOUNT_DELETED)
    @JvmField
    var accountDeleted: Boolean = false

    /**
     * 仅客态时传入, 该参数作用仅用于改善用户交互
     * #note 可以不传
     */
    @Autowired(name = MineManager.KEY_USERNAME)
    @JvmField
    var userName: String = ""

    private val pageTitle = mutableListOf("Posts", "Liked")

    companion object {
        const val TAB_POST = 0
        const val TAB_LIKE = 1
        const val TAB_WISHLIST = 2
    }

    private val OFFSET_5 = CommUtils.dip2px(5)
    private val OFFSET_60 = CommUtils.dip2px(60)
    private val OFFSET_55 = OFFSET_60 - OFFSET_5
    private val OFFSET_180 = CommUtils.dip2px(180)
    private val OFFSET_225 = CommUtils.dip2px(225)

    override fun initViewBinding(): ActivityPersonHomeBinding =
        ActivityPersonHomeBinding.inflate(layoutInflater)

    override fun initData() {
        super.initData()

        viewModel.pageType = pageType
        if (pageType == MineManager.PersonHomePageType.OTHER_USER && accountId == UserDataCenter.getAccountInfo()?.id) {
            // 修正页面类型，比如从关注页面-我自己-跳转
            pageType = MineManager.PersonHomePageType.MINE
        } else if (pageType == MineManager.PersonHomePageType.MINE
            && accountId.isNotEmpty()
            && accountId != UserDataCenter.getAccountInfo()?.id
        ) {
            // 修正页面类型，比如从通知链接或外部链接跳转
            pageType = MineManager.PersonHomePageType.OTHER_USER
        } else if (pageType == MineManager.PersonHomePageType.MINE
            && accountId.isEmpty()
        ) {
            // 修正accountId,比如进入页面什么参数也不传
            accountId = UserDataCenter.getAccountInfo()?.id ?: ""
        }
        viewModel.accountId = accountId
        viewModel.pageType = pageType
    }


    override fun initView() {
        super.initView()
        initTopView()

        /**初始化ViewPager和TabLayout===*/
        if (pageType == MineManager.PersonHomePageType.OTHER_USER) {
            pageTitle.add("Wishlist")
        }
        viewBinding.viewPager.adapter = object : FragmentStateAdapter(this) {
            override fun createFragment(position: Int): Fragment {
                return when (position) {
                    TAB_POST -> PostFragment.newInstance(pageType, accountId, accountDeleted)
                    TAB_LIKE -> LikeFragment.newInstance(pageType, accountId, accountDeleted)
                    else -> WishlistFragment.newInstance(accountId, accountDeleted)
                }
            }

            override fun getItemCount(): Int {
                return pageTitle.size
            }
        }
        //tabLayout关联viewpager
        TabLayoutMediator(viewBinding.tabLayout, viewBinding.viewPager) { tab, position ->
            tab.text = pageTitle[position]
        }.attach()

        initTabView()

        //默认选中第一个
        viewBinding.tabLayout.getTabAt(0)?.select()
    }

    /**初始化标题栏，头部部分*/
    private fun initTopView() {
        viewBinding.titleIvBack.click {
            finish()
        }

        viewBinding.titleIvUserHead.alpha = 0f
        viewBinding.appbarLayout.addOnOffsetChangedListener { appBarLayout: AppBarLayout, verticalOffset: Int ->
//            YYLogUtils.e(
//                "appbarHeightdp:" + CommUtils.px2dip(appBarLayout.height) + " getTotalScrollRangedp:" + CommUtils.px2dip(appBarLayout.totalScrollRange) + " offSetdp:" + CommUtils.px2dip(verticalOffset),
//                "dss"
//            )
            // 页面向上滑动,appbarLayout.verticalOffset=[0dp-60dp]，顶部标题栏头像的alpha=[0-1]
            if (verticalOffset.absoluteValue <= OFFSET_60) {
                viewBinding.titleIvUserHead.alpha =
                    verticalOffset.absoluteValue.toFloat() / OFFSET_60
            } else {
                viewBinding.titleIvUserHead.alpha = 1f
            }

            // 页面向上滑动,appbarLayout.verticalOffset=[0dp-180dp]，头部内容部分alpha=[1-0.2]
            // 255 = 180/0.8
            if (verticalOffset.absoluteValue <= OFFSET_180) {
                viewBinding.layoutHead.root.alpha =
                    1 - verticalOffset.absoluteValue.toFloat() / OFFSET_225
            }
        }

        viewBinding.titleIvShare.click {
            // 分享
            var userId: String? = null
            if (pageType == MineManager.PersonHomePageType.MINE) {
                userId = UserDataCenter.getAccountInfo()?.id
            } else {
                userId = accountId
            }
            if (userId.isNullOrEmpty()) {
                return@click
            }
            ShareDialog(
                mActivity,
                ShareUrlUtils().getPersonalHomeShareUrl(userId),
                shareCome = ShareTypeEnum.PERSONAL_HOME_SHARE
            ) {}.show(supportFragmentManager, "share")
        }

        if (pageType == MineManager.PersonHomePageType.MINE) {
            // 我的个人首页-视图绑定数据（我的信息已存在）
            setUserHeadImage(UserDataCenter.getAccountInfo()?.headImage)

            viewBinding.layoutHead.tvUserName.text =
                UserDataCenter.getAccountInfo()?.userName
                    ?: UserDataCenter.getAccountInfo()?.username ?: ""

            viewBinding.layoutHead.tvUserId.visibleOrGone(!UserDataCenter.getAccountInfo()?.uuid.isNullOrEmpty()) {
                buildSpannableString {
                    addText("ID:${UserDataCenter.getAccountInfo()?.uuid}")
                    addImage(
                        imageRes = R.mipmap.ic_copy,
                        verticalAlignment = 4,
                        maginLeft = CommUtils.dip2px(4),
                        width = CommUtils.dip2px(14),
                        height = CommUtils.dip2px(14)
                    )
                }
                viewBinding.layoutHead.tvUserId.setOnClickListener {
                    CommUtils.copyText(UserDataCenter.getAccountInfo()?.uuid)
                    toast(R.string.copy_successfully)
                }
            }
            viewBinding.layoutHead.iconArrow.visibleOrGone(true)

            // 主态-点击头像一行，跳转编辑页面
            viewBinding.layoutHead.layoutUserHeadRow.setOnClickListener {
                LoginManager.navigationToEditPersonalInfo(mActivity)
            }

            viewBinding.layoutHead.tvFollowingNum.text =
                FormatUtils.formatAccountDataNum(UserDataCenter.getAccountInfo()?.followAccountCount)
            viewBinding.layoutHead.tvFollowersNum.text =
                FormatUtils.formatAccountDataNum(UserDataCenter.getAccountInfo()?.fansCount)
            // 客态-查看用户粉丝和用户关注
            viewBinding.layoutHead.followingNumLay.setOnClickListener {
                MineManager.navigationToMineFollow(
                    mActivity,
                    MineManager.FollowPageTabType.TAB_FOLLOWING
                )
            }
            viewBinding.layoutHead.followersNumLay.setOnClickListener {
                MineManager.navigationToMineFollow(
                    mActivity,
                    MineManager.FollowPageTabType.TAB_FOLLOWERS
                )
            }

            // 主态-有简介显示，无简介显示提示信息
            viewBinding.layoutHead.tvPersonalProfile.visibleOrGone(true)
            setMinePersonalProfile(UserDataCenter.getAccountInfo()?.description)
        } else {
            // 客态-根据传入参数设置部分视图，然后等待数据加载
            viewBinding.layoutHead.tvUserName.text =
                if (accountDeleted) getString(R.string.account_deleted)
                else userName
        }
    }

    private fun setMinePersonalProfile(personalProfile: String?) {
        if (personalProfile.isNullOrEmpty()) {
            viewBinding.layoutHead.tvPersonalProfile.buildSpannableString {
                addText("Add your personal profile") {
                    setColor(CommUtils.getColor(R.color.sk_gray400))
                }
                addImage(
                    imageRes = R.drawable.ic_svg_edit_gray400,
                    verticalAlignment = 4,
                    maginLeft = 5.dp,
                    width = 14.dp,
                    height = 14.dp
                )
            }
            viewBinding.layoutHead.tvPersonalProfile.click {
                LoginManager.navigationToEditPersonalInfo(mActivity)
            }
        } else {
            viewBinding.layoutHead.tvPersonalProfile.text = personalProfile
            viewBinding.layoutHead.tvPersonalProfile.setOnClickListener(null)
        }
    }

    private var tabVH: TabViewHolder? = null
    private fun initTabView() {
        tabVH = null
        for (i in 0 until viewBinding.tabLayout.tabCount) {
            val tab = viewBinding.tabLayout.getTabAt(i)
            //给tab设置自定义布局
            tab!!.setCustomView(com.starblink.mine.R.layout.tab_item_person_home)
            tabVH = TabViewHolder(tab.customView!!)
            //填充数据
            tabVH!!.tvName.text = pageTitle[i]
            //默认选择第一项
            if (i == 0) {
                tabVH!!.setTabSelectedStyle()
            }
        }
        viewBinding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                TabViewHolder(tab.customView!!).setTabSelectedStyle()
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                TabViewHolder(tab.customView!!).setTabUnselectedStyle()
            }

            override fun onTabReselected(tab: TabLayout.Tab) {}
        })
    }

    override fun initObservable() {
        super.initObservable()
        iniEventListener()
        viewModel.userInfoLiveData.observe(this) { accountF ->
            // 客态-设置TabLayout的Tabs是否允许查看(需要放在前面，数量信息返回后需要根据锁图标显示情况，判断是否显示数量)
            if (!accountF.isPostOpen()) {
                tabVH = TabViewHolder(viewBinding.tabLayout.getTabAt(TAB_POST)!!.customView!!)
                tabVH!!.ivIcon.visibleOrGone(true)
            }
            if (!accountF.isLikeOpen()) {
                tabVH = TabViewHolder(viewBinding.tabLayout.getTabAt(TAB_LIKE)!!.customView!!)
                tabVH!!.ivIcon.visibleOrGone(true)
            }
            if (!accountF.isWishlistOpen()) {
                tabVH = TabViewHolder(viewBinding.tabLayout.getTabAt(TAB_WISHLIST)!!.customView!!)
                tabVH!!.ivIcon.visibleOrGone(true)
            }

            // 通知子页面Fragment
            sharedViewModel.userInfoLiveData.value = accountF

            // 客态-标题栏-显示更多
            viewBinding.titleIvMore.visible()
            viewBinding.titleIvMore.click {
                val dialog =
                    navigationTo(RoutePage.DialogFragment.PERSONAL_HOME_OBJECTIVE_MORE_DIALOG) {
                        withObject(RoutePage.ARG.USER_INFO, accountF)
                    } as PersonalHomeObjectiveMoreDialog
                dialog.show(
                    supportFragmentManager,
                    RoutePage.DialogFragment.PERSONAL_HOME_OBJECTIVE_MORE_DIALOG
                )
            }
            supportFragmentManager.setFragmentResultListener(
                RESULT_CLICK_BLOCK,
                this
            ) { _, bundle ->
                val res = bundle.getBoolean(ARG_RESULT, false)
                SKLogger.e("dss", "res=$res")
                if (res) {
                    showBlockConfirmDialog(accountF)
                }
            }

            // 客态-视图绑定数据
            setUserHeadImage(accountF.headImage)

            viewBinding.layoutHead.tvUserName.text =
                if (accountF.deleted == true) getString(R.string.account_deleted)
                else accountF.userName ?: accountF.username ?: ""

            viewBinding.layoutHead.tvUserId.visibleOrGone(!accountF.uuid.isNullOrEmpty()) {
                buildSpannableString {
                    addText("ID:${accountF.uuid}")
                    addImage(
                        imageRes = R.mipmap.ic_copy,
                        verticalAlignment = 4,
                        maginLeft = CommUtils.dip2px(4),
                        width = CommUtils.dip2px(14),
                        height = CommUtils.dip2px(14)
                    )
                }
                viewBinding.layoutHead.tvUserId.click {
                    CommUtils.copyText(accountF.uuid)
                    toast(R.string.copy_successfully)
                }
            }

            // 客态-用户粉丝和用户关注
            viewBinding.layoutHead.tvFollowingNum.text =
                FormatUtils.formatAccountDataNum(accountF.followAccountCount)
            viewBinding.layoutHead.tvFollowersNum.text =
                FormatUtils.formatAccountDataNum(accountF.fansCount)
            viewBinding.layoutHead.followingNumLay.click {
                clickFollowingOrFollowerLayout(
                    accountF,
                    MineManager.FollowPageTabType.TAB_FOLLOWING
                )
            }
            viewBinding.layoutHead.followersNumLay.click {
                clickFollowingOrFollowerLayout(
                    accountF,
                    MineManager.FollowPageTabType.TAB_FOLLOWERS
                )
            }

            // 设置关注状态，点击事件
            viewBinding.layoutHead.tvFollow.visibleOrGone((accountF.deleted == true).not() && accountF.relationCode in 0..3) {
                setFollowBtn(accountF)
            }

            // 客态-有简介显示，否则不显示
            viewBinding.layoutHead.tvPersonalProfile.visibleOrGone(!accountF.description.isNullOrEmpty()) {
                text = accountF.description
            }

            // 客态-如果用户已被拉黑，设置页面视图为拉黑状态
            if (accountF.blockFlag == true) {
                setPageView2BlockStatus()
            }
        }

        viewModel.userCountDataLiveData.observe(this) {
//            YYLogUtils.e("viewModel.userCountDataLiveData=${it.toString()}", "dss")
            // 客态，将数据传给Wishlist子页
            if (pageType == MineManager.PersonHomePageType.OTHER_USER) {
                sharedViewModel.userCountDataLiveData.value = it
            }
            // 主态客态相同
            viewBinding.layoutHead.tvLikesNum.text =
                FormatUtils.formatAccountDataNum(it.likedCount)
            viewBinding.layoutHead.tvFollowingNum.text =
                FormatUtils.formatAccountDataNum(it.followAccountCount)
            viewBinding.layoutHead.tvFollowersNum.text =
                FormatUtils.formatAccountDataNum(it.fansCount)

            tabVH = TabViewHolder(viewBinding.tabLayout.getTabAt(TAB_POST)!!.customView!!)
            if (tabVH!!.ivIcon.visibility == View.GONE) {
                tabVH!!.tvName.text = "${FormatUtils.formatAccountDataNum(it.postCount)} Posts"
            }

            tabVH = TabViewHolder(viewBinding.tabLayout.getTabAt(TAB_LIKE)!!.customView!!)
            if (tabVH!!.ivIcon.visibility == View.GONE) {
                tabVH!!.tvName.text = "${FormatUtils.formatAccountDataNum(it.likeCount)} Liked"
            }
        }

        viewModel.blockUserLiveData.observe(this) {
            if (it == true && viewModel.userInfoLiveData.value != null) {
                // 修改用户数据
                viewModel.userInfoLiveData.value!!.apolloValue("blockFlag", true)
                // 更新页面为拉黑状态
                setPageView2BlockStatus()
            }
        }
    }

    /**
     * 设置页面视图为拉黑状态
     */
    private fun setPageView2BlockStatus() {
        viewBinding.tabLayout.gone()
        viewBinding.viewPager.gone()
        viewBinding.layContentWhenBlock.visible()
    }

    private fun iniEventListener() {
        // 监听用户信息修改事件
        FlowBus.with<PersonInfoModified>(FlowConst.PERSON_INFO_MODIFIED_EVENT).register(this) {
            if (it.headImage != null) {
                setUserHeadImage(it.headImage)
            }
            if (it.username != null) {
                viewBinding.layoutHead.tvUserName.text = it.username
            }
            if (it.personProfile != null) {
                setMinePersonalProfile(it.personProfile)
            }
        }

        FlowBus.with<LikePostEvent>(FlowConst.LIKE_POST_EVENT).register(this) {
            // 我的个人首页，点赞发布事件，需要更新数量
            // 其他人的个人首页，点赞发布事件，仅影响到的用户需要更新数量
            if (pageType == MineManager.PersonHomePageType.MINE ||
                (pageType == MineManager.PersonHomePageType.OTHER_USER && it.posterId == accountId)
            ) {
//                SKLogger.e("dss", "PersonHomeActivity-LIKE_POST_EVENT")
                viewModel.getUserCountInfo()
            }
        }
        FlowBus.with<FollowUserEvent>(FlowConst.FOLLOW_USER_EVENT).register(this) {
            // 我的个人首页，关注事件，需要更新数量
            // 其他人的个人首页，关注事件，仅影响到的用户需要更新数量,更新关注状态
            if (pageType == MineManager.PersonHomePageType.MINE) {
//                SKLogger.e("dss", "PersonHomeActivity-FOLLOW_USER_EVENT-MINE")
                viewModel.getUserCountInfo()
            } else if (pageType == MineManager.PersonHomePageType.OTHER_USER && it.id == accountId) {
//                SKLogger.e("dss", "PersonHomeActivity-FOLLOW_USER_EVENT-OTHER_USER&it.id == accountId")
                viewModel.getUserCountInfo()
                setFollowState(it.relationCode)
            }
        }
    }

    override fun initLoad() {
        super.initLoad()
        viewModel.getUserInfo()
    }

    private fun showBlockConfirmDialog(accountF: AccountF) {
        ConfirmDialog.Builder(this)
            .setMessage("Block this user? They won't be able to see your profile or content on Guang.")
            .setCancelButton(R.string.cancel) { dialog, _ ->
                dialog.dismiss()
            }
            .setSureButton(R.string.confirm) { dialog, _ ->
                dialog.dismiss()
                viewModel.blockUser(accountF)
            }
            .setCanCancel(true)
            .create().show()
    }

    /**
     * 设置用户头像
     */
    private fun setUserHeadImage(url: String?) {
        ImageUtils.loadImage(
            mContext,
            url,
            viewBinding.layoutHead.ivUserHead,
            ImageUtils.placeholderAvatarImage,
            ImageUtils.placeholderAvatarImage
        )
        ImageUtils.loadImage(
            mContext,
            url,
            viewBinding.titleIvUserHead,
            ImageUtils.placeholderAvatarImage,
            ImageUtils.placeholderAvatarImage
        )
    }

    private fun setFollowState(relationCode: Int) {
        when (relationCode) {
            UserRelationCodeEnum.NOTHING.code, UserRelationCodeEnum.FANS.code -> {
                // 未关注他
                viewBinding.layoutHead.tvFollow.text =
                    CommUtils.getString(R.string.add_follow)
                viewBinding.layoutHead.tvFollow.isSelected = false
            }

            UserRelationCodeEnum.FOLLOW.code, UserRelationCodeEnum.BOTH.code -> {
                // 已关注他
                viewBinding.layoutHead.tvFollow.text =
                    CommUtils.getString(R.string.following)
                viewBinding.layoutHead.tvFollow.isSelected = true
            }
        }
    }

    private fun setFollowBtn(accountF: AccountF) {
        setFollowState(accountF.relationCode)
        viewBinding.layoutHead.tvFollow.click {
            if (accountF.blockFlag == true) {
                toast(com.starblink.basic.style.R.string.have_block)
                return@click
            }
            CommonMutateManage.followUser(
                mContext,
                accountF.id,
                accountF.relationCode,
                {
                    // 刷新状态
                    setFollowState(
                        if (PostUtils.followed(accountF.relationCode)) accountF.relationCode - 1
                        else accountF.relationCode + 1
                    )
                })
            { relationCode ->
                ApolloValSetExt.setApolloVal<AccountF>(
                    accountF,
                    "relationCode",
                    relationCode
                )
                setFollowState(relationCode)
            }
        }
    }

    private fun clickFollowingOrFollowerLayout(accountF: AccountF, tabType: Int) {
        if (accountF.deleted == true) return

        if (!accountF.isFansOpen() && !accountF.isFollowOpen()) {
            toast("The user has set the list private")
            return
        }

        navigationTo(RoutePage.Mine.FOLLOW) {
            withInt(MineManager.KEY_PAGE_TYPE, pageType)
            withInt(MineManager.KEY_TAB_TYPE, tabType)
            withObject(MineManager.KEY_ACCOUNT, accountF)
        }
    }
}